import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useSeatStore = defineStore('seat', () => {
  // 状态
  const seats = ref([])
  const selectedSeats = ref([])
  const seatLayout = ref({
    rows: 12,
    cols: 8,
    areas: [
      { name: '普通区', color: '#34C759', startRow: 0, endRow: 7 },
      { name: 'VIP区', color: '#FF9500', startRow: 8, endRow: 11 }
    ]
  })
  const loading = ref(false)
  const lastUpdateTime = ref(null)
  
  // 计算属性
  const totalSeats = computed(() => seats.value.length)
  
  const availableSeats = computed(() => {
    return seats.value.filter(seat => seat.status === 'available')
  })
  
  const occupiedSeats = computed(() => {
    return seats.value.filter(seat => seat.status === 'occupied')
  })
  
  const maintenanceSeats = computed(() => {
    return seats.value.filter(seat => seat.status === 'maintenance')
  })
  
  const seatStats = computed(() => ({
    total: totalSeats.value,
    available: availableSeats.value.length,
    occupied: occupiedSeats.value.length,
    maintenance: maintenanceSeats.value.length
  }))
  
  const selectedSeatInfo = computed(() => {
    if (selectedSeats.value.length === 0) return null
    return seats.value.find(seat => seat.id === selectedSeats.value[0])
  })
  
  // 方法
  const fetchSeats = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 这里应该是真实的API调用
      // const response = await uni.request({
      //   url: '/api/seats',
      //   method: 'GET'
      // })
      
      // 模拟成功响应
      lastUpdateTime.value = new Date()
      return { success: true }
    } catch (error) {
      console.error('获取座位信息失败:', error)
      return { success: false, message: '获取座位信息失败' }
    } finally {
      loading.value = false
    }
  }
  
  const selectSeat = (seatId) => {
    const seat = seats.value.find(s => s.id === seatId)
    if (!seat || seat.status !== 'available') {
      uni.showToast({
        title: '该座位不可选择',
        icon: 'none'
      })
      return false
    }
    
    // 单选模式 - 清除之前的选择
    selectedSeats.value = [seatId]
    return true
  }
  
  const unselectSeat = (seatId) => {
    const index = selectedSeats.value.indexOf(seatId)
    if (index > -1) {
      selectedSeats.value.splice(index, 1)
    }
  }
  
  const clearSelection = () => {
    selectedSeats.value = []
  }
  
  const getSeatById = (seatId) => {
    return seats.value.find(seat => seat.id === seatId)
  }
  
  const getSeatsByArea = (areaName) => {
    const area = seatLayout.value.areas.find(a => a.name === areaName)
    if (!area) return []
    
    return seats.value.filter(seat => {
      const row = Math.floor((seat.position - 1) / seatLayout.value.cols)
      return row >= area.startRow && row <= area.endRow
    })
  }
  
  const updateSeatStatus = (seatId, status, occupiedUntil = null) => {
    const seat = seats.value.find(s => s.id === seatId)
    if (seat) {
      seat.status = status
      seat.occupiedUntil = occupiedUntil
      seat.updatedAt = new Date()
      lastUpdateTime.value = new Date()
    }
  }
  
  const refreshSeats = async () => {
    // 模拟刷新座位状态
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 随机更新一些座位状态
    seats.value.forEach(seat => {
      if (Math.random() < 0.1) { // 10%概率状态变化
        if (seat.status === 'occupied' && Math.random() < 0.3) {
          seat.status = 'available'
          seat.occupiedUntil = null
        } else if (seat.status === 'available' && Math.random() < 0.2) {
          seat.status = 'occupied'
          seat.occupiedUntil = new Date(Date.now() + Math.random() * 4 * 60 * 60 * 1000)
        }
      }
    })
    
    lastUpdateTime.value = new Date()
    return { success: true }
  }
  
  // 初始化座位数据（模拟数据）
  const initMockSeats = () => {
    const mockSeats = []
    const totalSeats = seatLayout.value.rows * seatLayout.value.cols
    
    for (let i = 1; i <= totalSeats; i++) {
      const row = Math.floor((i - 1) / seatLayout.value.cols)
      const col = (i - 1) % seatLayout.value.cols
      
      // 确定座位区域和价格
      let area = '普通区'
      let price = 6 // 每小时价格
      
      if (row >= 8) {
        area = 'VIP区'
        price = 12
      }
      
      // 随机生成座位状态
      const statuses = ['available', 'occupied', 'maintenance']
      const weights = [0.65, 0.3, 0.05] // 65%空闲，30%占用，5%维修
      let randomStatus = 'available'
      const random = Math.random()
      
      if (random < weights[2]) {
        randomStatus = 'maintenance'
      } else if (random < weights[1] + weights[2]) {
        randomStatus = 'occupied'
      }
      
      // 生成座位号（A1, A2, B1, B2...）
      const seatNumber = `${String.fromCharCode(65 + row)}${col + 1}`
      
      mockSeats.push({
        id: i,
        number: seatNumber,
        position: i,
        row: row,
        col: col,
        area: area,
        status: randomStatus,
        price: price,
        equipment: {
          cpu: area === 'VIP区' ? 'Intel i7-12700K' : 'Intel i5-11400F',
          gpu: area === 'VIP区' ? 'RTX 4070' : 'GTX 1660 Super',
          memory: area === 'VIP区' ? '32GB DDR4' : '16GB DDR4',
          monitor: area === 'VIP区' ? '27寸 2K 144Hz' : '24寸 1080P 75Hz'
        },
        occupiedUntil: randomStatus === 'occupied' ? 
          new Date(Date.now() + Math.random() * 4 * 60 * 60 * 1000) : null,
        createdAt: new Date(),
        updatedAt: new Date()
      })
    }
    
    seats.value = mockSeats
    lastUpdateTime.value = new Date()
    
    console.log(`初始化了 ${mockSeats.length} 个座位`)
  }
  
  // 获取座位推荐
  const getRecommendedSeats = (preferences = {}) => {
    const { area, priceRange, equipment } = preferences
    
    let filteredSeats = availableSeats.value
    
    // 按区域筛选
    if (area && area !== 'all') {
      filteredSeats = filteredSeats.filter(seat => seat.area === area)
    }
    
    // 按价格筛选
    if (priceRange) {
      filteredSeats = filteredSeats.filter(seat => 
        seat.price >= priceRange.min && seat.price <= priceRange.max
      )
    }
    
    // 按设备要求筛选
    if (equipment) {
      filteredSeats = filteredSeats.filter(seat => {
        if (equipment.highPerformance && seat.area !== 'VIP区') return false
        return true
      })
    }
    
    // 随机排序并返回前5个
    return filteredSeats.sort(() => Math.random() - 0.5).slice(0, 5)
  }
  
  // 预约座位
  const reserveSeat = async (seatId, startTime, endTime) => {
    const seat = getSeatById(seatId)
    if (!seat || seat.status !== 'available') {
      return { success: false, message: '座位不可用' }
    }
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 更新座位状态
      updateSeatStatus(seatId, 'occupied', endTime)
      
      return { success: true, message: '预约成功' }
    } catch (error) {
      return { success: false, message: '预约失败' }
    }
  }
  
  return {
    // 状态
    seats,
    selectedSeats,
    seatLayout,
    loading,
    lastUpdateTime,
    
    // 计算属性
    totalSeats,
    availableSeats,
    occupiedSeats,
    maintenanceSeats,
    seatStats,
    selectedSeatInfo,
    
    // 方法
    fetchSeats,
    selectSeat,
    unselectSeat,
    clearSelection,
    getSeatById,
    getSeatsByArea,
    updateSeatStatus,
    refreshSeats,
    initMockSeats,
    getRecommendedSeats,
    reserveSeat
  }
})
